<template>
  <div class="sku">
    <h3>iphone 13</h3>
    <div v-for="(item, index) of processAttribute" :key="index">
      <div class="title" style="margin-bottom: 10px; margin-top: 10px">{{ item.title }}</div>
      <template v-for="(item1, index1) of item.attributeItem" :key="index1">
        <el-tag
          type="success"
          :class="[
            {
              active: item1.activity,
              disabled: item1.disabled,
            },
          ]"
          style="margin-right: 10px; cursor: pointer"
          @click="skuClickHandler(index, index1)"
          >{{ item1.name }}</el-tag
        >
      </template>
    </div>
    <div>当前选中的库存:{{ stock }}</div>
    <div
      >价格范围:
      <span v-if="minPrice == maxPrice">{{ maxPrice }}</span>
      <span v-else>{{ minPrice }}-{{ maxPrice }}</span>
    </div>
  </div>
</template>

<script setup>
  import { onMounted } from 'vue';
  import { SkuService } from '@/services';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  const skuAttribute = ref([]);
  const skuList = ref([]);
  const processAttribute = ref([]);
  const processSkuMap = ref({});
  const initData = () => {
    for (const item of skuAttribute.value) {
      let temp = {
        id: item.id,
        title: item.title,
      };
      temp.attributeItem = item.attributeItem
        .filter((it) => item.checkList.includes(it.id)) // 过滤有的属性
        .map((it) => {
          return {
            ...it,
            activity: false,
            disabled: itemquantity(it.name) <= 0, // 判断当前是否小于0的库存
            stock: itemquantity(it.name),
          };
        });
      processAttribute.value.push(temp);
    }
    // 对 skuList 数据进行加工，并存入 processSkuMap 中
    for (const item of skuList.value) {
      let combArr = arrayCombine(item.attributeValue.split(','));
      for (let j = 0; j < combArr.length; j++) {
        var key = combArr[j].join(',');
        if (processSkuMap.value[key]) {
          // 库存累加，价格添加进数组
          processSkuMap.value[key].stock += +item.stock;
          processSkuMap.value[key].prices.push(item.price);
        } else {
          processSkuMap.value[key] = {
            stock: +item.stock,
            prices: [item.price],
          };
        }
      }
    }
    // 计算下
    // skuCheck();
  };
  // 计算当前sku的库存
  const itemquantity = (item) => {
    let quantity = 0;
    skuList.value.forEach((element) => {
      var skuArr = element.attributeValue.split(',');
      if (skuArr.indexOf(item) != -1) {
        quantity += +element.stock;
      }
    });
    return quantity;
  };
  const arrayCombine = (targetArr) => {
    let resultArr = [];
    for (var n = 0; n <= targetArr.length; n++) {
      var flagArrs = getFlagArrs(targetArr.length, n);
      while (flagArrs.length) {
        var flagArr = flagArrs.shift();
        var combArr = Array(targetArr.length);
        for (var i = 0; i < targetArr.length; i++) {
          if (flagArr[i]) {
            combArr[i] = targetArr[i];
          }
        }
        resultArr.push(combArr);
      }
    }
    return resultArr;
  };

  const getFlagArrs = (m, n) => {
    let flagArrs = [];
    let flagArr = [];
    let isEnd = false;
    for (let i = 0; i < m; i++) {
      flagArr[i] = i < n ? 1 : 0;
    }
    flagArrs.push(flagArr.concat());
    // 当n不等于0并且m大于n的时候进入
    if (n && m > n) {
      while (!isEnd) {
        var leftCnt = 0;
        for (var i = 0; i < m - 1; i++) {
          if (flagArr[i] == 1 && flagArr[i + 1] == 0) {
            for (var j = 0; j < i; j++) {
              flagArr[j] = j < leftCnt ? 1 : 0;
            }
            flagArr[i] = 0;
            flagArr[i + 1] = 1;
            var aTmp = flagArr.concat();
            flagArrs.push(aTmp);
            if (aTmp.slice(-n).join('').indexOf('0') == -1) {
              isEnd = true;
            }
            break;
          }
          flagArr[i] == 1 && leftCnt++;
        }
      }
    }
    return flagArrs;
  };
  // 点击sku
  const skuClickHandler = (key1, key2) => {
    console.log(key1, key2, '点击了', processAttribute.value[key1]);
    // 如果不是被禁用的时候才执行
    if (!processAttribute.value[key1].attributeItem[key2].disabled) {
      // 选择和取消选中
      processAttribute.value[key1].attributeItem.map((item, index) => {
        item.activity = index == key2 ? !item.activity : false;
      });
      // 检查当前的sku是否有库存
      skuCheck();
      // 每次点击的时候判断禁用
      getStockPrice();
    }
  };
  // 当前选中的sku的库存机最小单价最大单价
  const stock = ref(0);
  const minPrice = ref(null);
  const maxPrice = ref(null);
  const skuCheck = () => {
    let sku = [];
    processAttribute.value.map((attr) => {
      let name = '';
      attr.attributeItem.map((item) => {
        console.log(item, '111');
        if (item.activity) {
          name = item.name;
        }
      });
      sku.push(name);
    });
    console.log(sku, '选中的的值', sku.join(','));
    stock.value = processSkuMap.value[sku.join(',')].stock;
    minPrice.value = Math.min.apply(Math, processSkuMap.value[sku.join(',')].prices);
    maxPrice.value = Math.max.apply(Math, processSkuMap.value[sku.join(',')].prices);
  };
  // 点击的时候判断库存禁用
  const getStockPrice = () => {
    processAttribute.value.map((attr) => {
      attr.attributeItem.map((item) => {
        item.disabled = itemquantity(item.name) <= 0;
      });
    });
    let count = 0;
    let i = 0;
    processAttribute.value.map((attr, index) => {
      let flag = false;
      attr.attributeItem.map((item) => {
        if (item.activity) {
          flag = true;
        }
      });
      if (!flag) {
        count += 1;
        i = index;
      }
    });
    // 当只有一组规格没选时
    if (count == 1) {
      processAttribute.value[i].attributeItem.map((item) => {
        let sku = [];
        let text = item.name;
        processAttribute.value.map((attr, index) => {
          if (index != i) {
            attr.attributeItem.map((item2) => {
              if (item2.activity) {
                sku.push(item2.name);
              }
            });
          } else {
            sku.push(text);
          }
        });
        if (processSkuMap.value[sku.join(',')].stock == 0) {
          item.disabled = true;
        }
      });
    }
    // 当所有规格都有选时
    if (count == 0) {
      processAttribute.value.map((attr, index) => {
        let i = index;
        processAttribute.value[index].attributeItem.map((item) => {
          if (!item.activity) {
            let sku = [];
            let text = item.name;
            processAttribute.value.map((list, index) => {
              if (index != i) {
                list.attributeItem.map((item2) => {
                  if (item2.activity) {
                    sku.push(item2.name);
                  }
                });
              } else {
                sku.push(text);
              }
            });
            if (processSkuMap.value[sku.join(',')].stock == 0) {
              item.disabled = true;
            }
          }
        });
      });
    }
  };
  const initSkuData = async () => {
    const { result } = await SkuService.getSkuByIdApi(route.query.id);
    // console.log(data);
    console.log(result.skuAttribute, '111');
    skuAttribute.value = result.skuAttribute;
    skuList.value = result.skuList;
  };
  onMounted(async () => {
    await initSkuData();
    initData();
  });
</script>

<style lang="scss" scoped>
  .sku {
    .active {
      background: skyblue;
      color: #fff;
      border: none;
    }
    .disabled {
      background: #ddd;
    }
  }
</style>
